<template>
  <div class="user-profile">
    <!-- <AppHeader /> -->

    <main class="main-content">
      <div class="container">
        <div class="profile-layout">
          <!-- 左侧导航 -->
          <div class="sidebar">
            <div class="user-card">
              <div class="avatar-section">
                <el-avatar
                  :size="80"
                  :src="currentUser?.avatarUrl"
                  class="user-avatar"
                >
                  {{ currentUser?.nickname?.charAt(0) }}
                </el-avatar>
              </div>
              <div class="user-actions">
                <el-button
                  size="default"
                  @click="showAvatarDialog = true"
                  type="primary"
                >
                  更换头像</el-button
                >
              </div>
              <!-- <div class="user-info">
                <h3>{{ currentUser?.nickname }}</h3>
                <p>{{ currentUser?.email }}</p>
              </div> -->
            </div>

            <el-menu :default-active="activeMenu" @select="handleMenuSelect">
              <el-menu-item index="basic">
                <el-icon>
                  <User />
                </el-icon>
                基础信息
              </el-menu-item>
              <el-menu-item index="study">
                <el-icon>
                  <Reading />
                </el-icon>
                学习信息
              </el-menu-item>
              <el-menu-item index="social">
                <el-icon>
                  <Star />
                </el-icon>
                社交信息
              </el-menu-item>
              <el-menu-item index="security">
                <el-icon>
                  <Lock />
                </el-icon>
                安全设置
              </el-menu-item>
              <!-- <el-menu-item index="preferences">
                <el-icon>
                  <Setting />
                </el-icon>
                偏好设置
              </el-menu-item> -->
            </el-menu>
            <el-button
              style="margin-left: 35px"
              type="primary"
              @click="logOut"
              class="change-avatar-button"
              >退出登录</el-button
            >
          </div>

          <!-- 右侧内容 -->
          <div class="content-area">
            <!-- 基础信息 -->
            <div v-if="activeMenu === 'basic'" class="section">
              <h2>基础信息</h2>
              <el-form
                :model="basicForm"
                :rules="basicFormRules"
                ref="basicFormRef"
                label-width="100px"
                class="profile-form"
              >
               <el-form-item label="用户名">
                  <el-input v-model="basicForm.username" disabled />
                </el-form-item>
                <el-form-item label="昵称">
                  <el-input v-model="basicForm.nickname" />
                </el-form-item>
               
                <el-form-item label="邮箱">
                  <el-input v-model="basicForm.email" />
                </el-form-item>
                <el-form-item label="手机号" prop="userPhone">
                  <el-input v-model="basicForm.userPhone" />
                  <el-text type="info" size="small" class="phone-hint">请填写完整手机号码</el-text>
                </el-form-item>
                  
                <el-form-item label="性别">
                  <el-radio-group v-model="basicForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="0">女</el-radio>
                    <!-- <el-radio label="保密">保密</el-radio> -->
                  </el-radio-group>
              
                 
                </el-form-item>
                   
              
                
            
                <el-form-item>
                  <el-button type="primary" @click="saveBasicInfo"
                    >保存</el-button
                  >
                </el-form-item>
              </el-form>
            </div>

            <!-- 学习信息 -->
            <div v-if="activeMenu === 'study'" class="section">
              <h2>学习信息</h2>
              <el-form
                :model="studyForm"
                :rules="studyFormRules"
                label-width="100px"
                class="profile-form"
                ref="studyFormRef"
              >
                <el-form-item label="学习科目" prop="frontSubjectList">
                  <el-input-tag
                    v-model="studyForm.frontSubjectList"
                    placeholder="请填写您想要学习的科目"
                  >
                    <template #tag="{ value }">
                      <div class="flex items-center">
                        <el-icon class="mr-1">
                          <ElementPlus />
                        </el-icon>
                        <span>{{ value }}</span>
                      </div>
                    </template>
                  </el-input-tag>
                </el-form-item>
                <el-form-item label="学习目标">
                  <el-input
                    v-model="studyForm.studyGoal"
                    type="textarea"
                    :rows="4"
                    placeholder="描述你的学习目标"
                  />
                </el-form-item>
                <el-form-item label="学历">
                  <el-input
                    v-model="studyForm.education"
                    placeholder="请输入您的学历"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item label="每日学习时间:">
                  <!-- 展示每日学习的时间 -->
                  <el-text> {{ studyForm.studyTime }} 分钟 </el-text>
                  <!-- <el-select
                    v-model="studyForm.studyTime"
                    placeholder="选择每日学习时间"
                  >
                    <el-option label="1-2小时" value="1-2小时" />
                    <el-option label="2-4小时" value="2-4小时" />
                    <el-option label="4-6小时" value="4-6小时" />
                    <el-option label="6小时以上" value="6小时以上" />
                  </el-select> -->
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="saveStudyInfo"
                    >保存</el-button
                  >
                </el-form-item>
              </el-form>
            </div>

            <!-- 社交信息 -->
            <div v-if="activeMenu === 'social'" class="section">
              <h2>社交信息</h2>
              <el-form
                :model="socialForm"
                label-width="100px"
                class="profile-form"
              >
                <el-form-item label="毕业院校">
                  <el-input v-model="socialForm.educationInfo" placeholder="请输入毕业院校" />
                </el-form-item>
                <el-form-item label="职业">
                  <el-input v-model="socialForm.workInfo" placeholder="请输入职业" />
                </el-form-item>
                <el-form-item label="兴趣爱好">
                  <el-select
                    v-model="socialForm.interestInfo"
                    placeholder="请选择兴趣爱好"
                  >
                    <el-option label="游泳" value="游泳" />
                    <el-option label="健身" value="健身" />
                    <el-option label="阅读" value="阅读" />
                    <el-option label="户外" value="户外" />
                    <el-option label="探险" value="探险" />
                  </el-select>
                </el-form-item>
                <el-form-item label="所在地">
                  <el-select
                    v-model="socialForm.locationInfo"
                    placeholder="请选择所在地"
                  >
                    <el-option label="成都" value="成都" />
                    <el-option label="北京" value="北京" />
                    <el-option label="上海" value="上海" />
                    <el-option label="广州" value="广州" />
                    <el-option label="深圳" value="深圳" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveSocialInfo"
                    >保存</el-button
                  >
                </el-form-item>
              </el-form>
            </div>

            <!-- 安全设置 -->
            <div v-if="activeMenu === 'security'" class="section">
              <h2>安全设置</h2>
              <div class="security-options">
                <div class="security-item">
                  <div class="security-info">
                    <h4>修改密码</h4>
                    <p>定期修改密码，保护账号安全</p>
                  </div>
                  <el-button @click="showPasswordDialog = true">修改</el-button>
                </div>
                <!-- <div class="security-item">
                  <div class="security-info">
                    <h4>绑定手机</h4>
                    <p>已绑定: {{ currentUser?.userPhone || "未绑定" }}</p>
                  </div>
                  <el-button>{{
                    currentUser?.userPhone ? "更换" : "绑定"
                  }}</el-button>
                </div> -->
                <!-- <div class="security-item">
                  <div class="security-info">
                    <h4>绑定邮箱</h4>
                    <p>已绑定: {{ currentUser?.email || "未绑定" }}</p>
                  </div>
                  <el-button>{{
                    currentUser?.email ? "更换" : "绑定"
                  }}</el-button>
                </div> -->
              </div>
            </div>

            <!-- 偏好设置 -->
            <!-- <div v-if="activeMenu === 'preferences'" class="section">
              <h2>偏好设置</h2>
              <div class="preferences-section">
                <h4>自习室默认设置</h4>
                <el-form label-width="150px">
                  <el-form-item label="默认关闭摄像头">
                    <el-switch v-model="preferences.defaultCameraOff" />
                  </el-form-item>
                  <el-form-item label="默认关闭麦克风">
                    <el-switch v-model="preferences.defaultMicOff" />
                  </el-form-item>
                  <el-form-item label="隐藏个人信息">
                    <el-switch v-model="preferences.hidePersonalInfo" />
                  </el-form-item>
                </el-form>
              </div>

              <div class="preferences-section">
                <h4>AI助手设置</h4>
                <el-form label-width="150px">
                  <el-form-item label="启用AI学习提醒">
                    <el-switch v-model="preferences.enableAIReminder" />
                  </el-form-item>
                  <el-form-item label="自动生成学习计划">
                    <el-switch v-model="preferences.autoGeneratePlan" />
                  </el-form-item>
                </el-form>
              </div>

              <el-button type="primary" @click="savePreferences"
                >保存设置</el-button
              >
            </div> -->
          </div>
        </div>
      </div>
    </main>

    <AppFooter />

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px" >
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="当前密码">
          <el-input v-model="passwordForm.currentPassword" type="password"  clearable/>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password"  clearable/>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="showAvatarDialog" title="更换头像" width="400px">
      <div class="avatar-upload">
        <el-upload
          :show-file-list="false"
          :auto-upload="false"
          @change="handleAvatarChange"
          :before-upload="beforeAvatarUpload"
          action="#"
          accept="image/jpeg,image/png"
        >
          <el-avatar :size="120" :src="avatarPreview">
            <el-icon>
              <Plus />
            </el-icon>
          </el-avatar>
        </el-upload>
        <p>点击上传头像</p>
      </div>
      <template #footer>
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAvatar" :disabled="!avatarFile"
          >保存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useUserStore,FormInstance  } from "@/stores";
// import AppHeader from '@/components/layout/Header.vue'
// import AppFooter from '@/components/layout/Footer.vue'
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { User, Reading, Lock, Setting, Plus, Star } from "@element-plus/icons-vue";
import { uploadAvatar } from "@/api/user";
import { useRouter } from "vue-router";
import { updateStudyInfo } from "@/api/studyInfo";
import { insertStudyInfo } from "@/api/studyInfo";
import { updateSocialInfo , getSocialData } from "@/api/user";
import { selectStudyInfoVoByUserId } from "@/api/studyInfo";
import { updateUserInfo } from "@/api/user";
import { updatePassword } from "@/api/user";
const previewAvatarUrl = ref(""); // 用于预览上传的头像
const newAvatarFile = ref<File | null>(null); // 存储上传的文件对象
const userStore = useUserStore();
const router = useRouter();

const activeMenu = ref("basic");
const showPasswordDialog = ref(false);
const showAvatarDialog = ref(false);
const avatarUrl = ref("");
const avatarPreview = ref<string | null>(null);
const avatarFile = ref<File | null>(null);

const currentUser = computed(() => userStore.currentUser);
const basicFormRef = ref<FormInstance>();
// 添加表单引用
const studyFormRef = ref();

// 定义学习信息表单的验证规则
const studyFormRules: FormRules = {
  frontSubjectList: [
    {
      required: true,
      message: "学习科目不能为空",
      trigger: "blur",
    },
  ],
};

const basicForm = reactive({
  nickname: "",
  username: "",
  email: "",
  userPhone: "",
  gender: 1,
  education: "",
});
const subjectList = ref([]); // 学科列表

const studyForm = reactive({
  subjectName: "", // 学习科目
  studyGoal: "",
  studyTime: 0, //学习分钟数
  education: "", // 学历
  frontSubjectList: [], // 学科列表
});

// 社交信息表单
const socialForm = reactive({
  usId: null, // 社交信息ID
  userId: currentUser.value.userId, // 用户ID
  educationInfo: "", // 毕业院校
  workInfo: "", // 职业
  interestInfo: "", // 兴趣爱好
  locationInfo: "", // 所在地
});

const passwordForm = reactive({
  currentPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const preferences = reactive({
  defaultCameraOff: true,
  defaultMicOff: true,
  hidePersonalInfo: false,
  enableAIReminder: true,
  autoGeneratePlan: true,
});

onMounted(() => {
  loadUserData();
  //页面加载时获取学习信息
  getStudyInfoAndSubject();
  // 获取社交信息
  fetchSocialData();
});
const getStudyInfoAndSubject = async () => {
  //获取userid
  const userdata = currentUser.value;
  console.log("用户信息为：", userdata);

  const res = await selectStudyInfoVoByUserId({
    userId: userdata.userId,
  });
  console.log("学习信息数据是:", res);
  if (res.code === 200) {
    //将查询到的学习信息赋值给studyForm
    const subjectList = res.data.subjectList; // 学科列表
    console.log("学科列表是:", subjectList);
    //遍历学科列表subjectList
    for (let i = 0; i < subjectList.length; i++) {
      const subjectObj = subjectList[i];
      studyForm.frontSubjectList.push(subjectObj.subjectName);
    }

    //遍历frontSubjectList，获取用户最新选择的学科

    studyForm.studyGoal = res.data.studyGoal;
    studyForm.education = res.data.education;
    studyForm.studyTime = res.data.studyTime;

    //更新状态机中的hasSaveStudyInfo为true
    userStore.updateProfile({ hasSaveStudyInfo: true });
  } else {
    console.error("查询学习信息失败:", res.message);
  }
};

const loadUserData = () => {
  console.log("加载用户数据...", currentUser.value);

  // 从用户状态中获取当前用户信息
  if (currentUser.value) {
    basicForm.nickname = currentUser.value.nickname;
    basicForm.username = currentUser.value.username;
    basicForm.email = currentUser.value.email;
    basicForm.userPhone = currentUser.value.userPhone;
     // 设置默认性别为男(1)，如果用户数据中没有设置性别
    basicForm.gender = currentUser.value.gender ?? 1;
    basicForm.education = currentUser.value.education;
  }else {
    // 如果没有用户数据，也默认设置为男
    basicForm.gender = 1;
  }
};
const validatePhone = (rule: any, value: any, callback: any) => {
  // 手机号正则表达式
  const phoneRegex = /^1[3-9]\d{9}$/;
  
  if (value && !phoneRegex.test(value)) {
    callback(new Error("请输入正确的手机号格式"));
  } else {
    callback();
  }
};
// 添加基础信息表单验证规则
const basicFormRules: FormRules = {
  userPhone: [
    { validator: validatePhone, trigger: "blur" }
  ]
};

const logOut = () => {
  userStore.logout();
};

const handleMenuSelect = (index: string) => {
  activeMenu.value = index;
};

const saveBasicInfo = async() => {
 // 先进行表单验证
  if (basicFormRef.value) {
    try {
      await basicFormRef.value.validate();
    } catch (error) {
      ElMessage.error("请检查表单信息是否正确");
      return;
    }
  }




 try {
  //从状态机中获取用户id
  const userId = userStore.currentUser.userId;
    const res = await updateUserInfo({
      ...basicForm,
      userId:userId
    });
    console.log("修改的信息为", res);
    
    if (res.code === 200) {
      // 更新用户状态
      userStore.updateProfile(basicForm);
      ElMessage.success("基础信息保存成功");
    } else {
      ElMessage.error(res.msg || "保存失败");
    }
  } catch (error) {
    ElMessage.error("保存失败");
    console.error("保存基础信息失败:", error);
  }
  
};

const saveStudyInfo = async () => {
  // 验证学习信息表单
  if (!studyFormRef.value) return;

  try {
    await studyFormRef.value.validate();
  } catch (error) {
    console.log("表单验证失败:", error);
    ElMessage.error("请填写必填项");
    return;
  }
  userStore.updateProfile({
    frontSubjectList: studyForm.frontSubjectList,
    studyGoal: studyForm.studyGoal,
    // studyTime: studyForm.studyTime,
    education: studyForm.education, // 保存学历信息
  });
  //从状态机中获取当前用户信息
  const userInfo = userStore.currentUser;
  console.log("当前用户信息:", userInfo);
  //判断studyGoal如果有值，则更新用户信息，没有值则插入用户信息,初始用户刚进来的时候studyGoal是空的
  try {
    if (userInfo.hasSaveStudyInfo) {
      //表示已经保存过学习信息
      //更新用户的学习信息
      console.log("更新用户学习信息------");

      const res = await updateStudyInfo({
        userId: userInfo.userId,
        frontSubjectList: studyForm.frontSubjectList,
        studyGoal: studyForm.studyGoal,
        education: studyForm.education,
      });
      console.log("更新学习信息响应:", res);
      //把

      ElMessage.success("学习信息修改成功");
    } else {
      //表示第一次保存学习信息
      //插入用户的学习信息
      console.log("插入用户学习信息------");

      const res = await insertStudyInfo({
        userId: userInfo.userId,
        frontSubjectList: studyForm.frontSubjectList,
        studyGoal: studyForm.studyGoal,
        education: studyForm.education,
      });
      console.log("新增学习信息响应:", res);
      //更新状态机中的hasSaveStudyInfo为true
      userStore.updateProfile({ hasSaveStudyInfo: true });

      ElMessage.success("学习信息保存成功");
    }
  } catch (error) {
    console.error("保存学习信息失败:", error);
    ElMessage.error("学习信息保存失败");
  }

  // ElMessage.success("学习信息保存成功");
};

const changePassword = async() => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error("两次输入的密码不一致");
    return;
  }

  if (passwordForm.newPassword.length < 6) {
    ElMessage.error("新密码长度不能少于6位");
    return;
  }

const res=await updatePassword({
    userId: userStore.currentUser.userId,
   
    password: passwordForm.newPassword,
  });
  console.log("修改密码操作",res);
  if (res.code==200) {
    ElMessage.success("密码修改成功");
  }else {
    ElMessage.error("密码修改失败");
  }

  

  // 模拟修改密码
  showPasswordDialog.value = false;
  

  // 重置表单
  Object.assign(passwordForm, {
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
};

const savePreferences = () => {
  ElMessage.success("偏好设置保存成功");
};
// 头像变更处理
const handleAvatarChange = (file: any) => {
  console.log("头像文件变更:", file);

  // 创建预览URL
  avatarPreview.value = URL.createObjectURL(file.raw);
  // 保存文件对象
  avatarFile.value = file.raw;
};

// 保存头像
const saveAvatar = async () => {
  if (!avatarFile.value) {
    ElMessage.warning("请先选择头像文件");
    return;
  }

  try {
    //获取状态机中当前用户id
    const userId = userStore.currentUser?.userId;
    console.log("当前用户id:", userId);

    // 创建FormData对象
    const formData = new FormData();
    formData.append("file", avatarFile.value);
    formData.append("userId", userId.toString());
    console.log("formData:", formData);
    // // 调用上传接口
    const res = await uploadAvatar(formData); // 调用接口上传
    console.log("上传结果:", res);

    // ✅ 假设接口返回了新头像的 URL，比如 res.data.avatarUrl
    const newAvatarUrl = res.data.url;

    // 更新用户信息中的头像（触发页面头像更新）
    userStore.updateProfile({ avatarUrl: newAvatarUrl });

    // ✅ 更新预览头像
    avatarPreview.value = newAvatarUrl;

    ElMessage.success("头像上传成功");
    showAvatarDialog.value = false;
    // 可选：刷新用户信息或更新头像URL
  } catch (error) {
    ElMessage.error("头像上传失败");
    console.error("头像上传失败:", error);
  }
};
const beforeAvatarUpload = (file: File) => {
  // const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  // const isLt2M = file.size / 1024 / 1024 < 2;

  // if (!isJPG) {
  //   ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
  // }
  // if (!isLt2M) {
  //   ElMessage.error("上传头像图片大小不能超过 2MB!");
  // }
  // return isJPG && isLt2M;
  const isValidType = ["image/jpeg", "image/png"].includes(file.type);
  const isValidSize = file.size / 1024 / 1024 < 2;

  if (!isValidType) {
    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
  }
  if (!isValidSize) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }

  return isValidType && isValidSize;
};

const handleAvatarSuccess = (response: any, file: any) => {
  avatarUrl.value = URL.createObjectURL(file.raw);
};
// 保存社交信息
const saveSocialInfo = async () => {
  try {
    await updateSocialInfo(socialForm);
    ElMessage.success("社交信息保存成功");
  } catch (error) {
    console.error("保存社交信息失败:", error);
    ElMessage.error("社交信息保存失败");
  }
};
// 获取用户社交信息
const fetchSocialData = async () => {
  try {
    const userId = currentUser.value.userId;
    const res = await getSocialData(userId);
    console.log("获取社交信息响应:", res);
    
    if (res.code === 200) {
      Object.assign(socialForm, res.data); // 回显社交信息表单
    } else {
      console.error("获取社交信息失败:", res.message);
    }
  } catch (error) {
    console.error("获取社交信息异常:", error);
  }
};
</script>

<style scoped>
.user-profile {
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
}

.profile-layout {
  display: flex;
  gap: 40px;
}

.sidebar {
  width: 280px;
}

.user-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.avatar-section {
  margin-bottom: 20px;
}

.user-avatar {
  margin-bottom: 12px;
}

.user-info h3 {
  margin-bottom: 8px;
  color: #2c3e50;
}

.user-info p {
  color: #7f8c8d;
  margin: 0;
}

.content-area {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section h2 {
  margin-bottom: 30px;
  color: #2c3e50;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.profile-form {
  max-width: 600px;
}

.security-options {
  max-width: 600px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-info h4 {
  margin-bottom: 4px;
  color: #2c3e50;
}

.security-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.preferences-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.preferences-section h4 {
  margin-bottom: 20px;
  color: #2c3e50;
}

.avatar-upload {
  text-align: center;
}

.avatar-upload p {
  margin-top: 16px;
  color: #7f8c8d;
}

@media (max-width: 768px) {
  .profile-layout {
    flex-direction: column;
    gap: 20px;
  }

  .sidebar {
    width: 100%;
  }

  .content-area {
    padding: 20px;
  }
}
.phone-hint {
  display: block;
  margin-top: 4px;
  margin-left: 0; /* 紧贴输入框开头 */
  line-height: 1.2;
}

.phone-hint :deep(.el-text) {
  font-size: 12px;
}
</style>
